#include <memory>

#include "Socket.hpp"
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

std::string SuffixToType(const std::string &suffix)
{
    if (suffix == ".html")
        return "text/html";
    else if (suffix == ".jpg")
        return "image/jpeg";
    else if (suffix == ".png")
        return "image/png";
    return "";
}

std::string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK"; // 请求成功。一般用于GET与POST请求
    case 301:
        return "Moved Permanently"; // 永久移动。请求的资源已被永久的移动到新URI，返回信息会包括新的URI，浏览器会自动定向到新URI。今后任何新的请求都应使用新的URI代替
    case 307:
        return "Temporary Redirect"; // 临时重定向。与302类似。使用GET请求重定向
    case 403:
        return "Forbidden"; // 服务器理解请求客户端的请求，但是拒绝执行此请求
    case 404:
        return "Not Found"; // 服务器无法根据客户端的请求找到资源（网页）。通过此代码，网站设计人员可设置"您所请求的资源无法找到"的个性页面
    case 500:
        return "Internal Server Error"; // 服务器内部错误，无法完成请求
    default:
        return "UnKnown";
    }
}

std::string HandlerRequest(std::string &inbufferstream)
{
    HttpRequest req;

    req.Deserialize(inbufferstream);
    req.Parse();
    req.Degub();
    int code = 200;

    std::string content;

    content = req.GetFileContent(req.Path());
    if (content.empty())
    {
        code = 404;
        content = req.Get_404_Content();
    }

    HttpResponse resp;
    resp.SetCode(code);
    resp.SetDesc(CodetoDesc(code)); // 设置状态码

    resp.Make_Status_Line(); // 设置状态行  "Http/1.0 200 OK\r\n";
    std::string content_len_str = "Content-Length: " + std::to_string(content.size()) + "\r\n";
    resp.AddHeader(content_len_str); // 设置正文内容长度词条
    std::string content_type_str = "Content-Type: " + SuffixToType(req.Suffix()) + "\r\n";
    resp.AddHeader(content_type_str); // 设置获取资源的后缀名

    //添加 Cookie
    std::string name_cookie = "Set-Cookie: username=zhangsan\r\n";
    resp.AddHeader(name_cookie);
    std::string password_cookie = "Set-Cookie: password=123456\r\n";
    resp.AddHeader(password_cookie);
    std::string status_cookie = "Set-Cookie: status=logined\r\n";
    resp.AddHeader(status_cookie);

    resp.AddContent(content);

    // 返回序列化后的报文
    return resp.Serialize();

    // std::cout<<"suffix: "<<req.Suffix()<<" Type: "<<SuffixToType(req.Suffix())<<std::endl;
    // std::cout<<std::endl<<std::endl;
    // if (!content.empty())
    // {
    //     std::string httpstatusline = "Http/1.0 200 OK\r\n";
    //     std::string httpresponse = httpstatusline + /* httpstatusline1 + httpstatusLanguage +*/ httpheader + content;
    //     return httpresponse;
    // }
    // return "";

    // if(req.Url() == "/favicon.ico")  // 进行两次请求，第一二次为 /favicon.ico 时需要返回 ""
    // return "";
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage->  " << argv[0] << " port" << std::endl;
        return 0;
    }

    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> Tcp_server = std::make_unique<TcpServer>(localport, HandlerRequest);

    Tcp_server->Loop();
}